package org.hj.modules.generatecode.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.vo.LoginUser;
import org.hj.modules.generatecode.entity.ViewModule;
import org.hj.modules.generatecode.entity.ViewUiproperties;
import org.hj.modules.generatecode.service.IViewUipropertiesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.hj.modules.generatecode.util.DatabaseUtil;
import org.hj.modules.generatecode.vo.DatabaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: UI属性
 * @Author: gaobw
 * @Date: 2020-06-16
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "UI属性")
@RestController
@RequestMapping("/generatecode/viewUiproperties")
public class ViewUipropertiesController {
    @Autowired
    private IViewUipropertiesService viewUipropertiesService;

    private DatabaseUtil databaseUtil;


    /**
     * 分页列表查询
     *
     * @param viewUiproperties
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "UI属性-分页列表查询")
    @ApiOperation(value = "UI属性-分页列表查询", notes = "UI属性-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ViewUiproperties>> queryPageList(ViewUiproperties viewUiproperties,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        Result<IPage<ViewUiproperties>> result = new Result<IPage<ViewUiproperties>>();
        QueryWrapper<ViewUiproperties> queryWrapper = QueryGenerator.initQueryWrapper(viewUiproperties, req.getParameterMap());
        queryWrapper.orderByDesc("ui_order");
        Page<ViewUiproperties> page = new Page<ViewUiproperties>(pageNo, pageSize);
        IPage<ViewUiproperties> pageList = viewUipropertiesService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param viewUiproperties
     * @return
     */
    @AutoLog(value = "UI属性-添加")
    @ApiOperation(value = "UI属性-添加", notes = "UI属性-添加")
    @PostMapping(value = "/add")
    public Result<ViewUiproperties> add(@RequestBody ViewUiproperties viewUiproperties) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        try {
            viewUipropertiesService.save(viewUiproperties);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param viewUiproperties
     * @return
     */
    @AutoLog(value = "UI属性-编辑")
    @ApiOperation(value = "UI属性-编辑", notes = "UI属性-编辑")
    @PutMapping(value = "/edit")
    public Result<ViewUiproperties> edit(@RequestBody ViewUiproperties viewUiproperties) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        ViewUiproperties viewUipropertiesEntity = viewUipropertiesService.getById(viewUiproperties.getId());
        if (viewUipropertiesEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = viewUipropertiesService.updateById(viewUiproperties);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "UI属性-通过id删除")
    @ApiOperation(value = "UI属性-通过id删除", notes = "UI属性-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<ViewUiproperties> delete(@RequestParam(name = "id", required = true) String id) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        ViewUiproperties viewUiproperties = viewUipropertiesService.getById(id);
        if (viewUiproperties == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = viewUipropertiesService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "UI属性-批量删除")
    @ApiOperation(value = "UI属性-批量删除", notes = "UI属性-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<ViewUiproperties> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.viewUipropertiesService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "UI属性-通过id查询")
    @ApiOperation(value = "UI属性-通过id查询", notes = "UI属性-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ViewUiproperties> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        ViewUiproperties viewUiproperties = viewUipropertiesService.getById(id);
        if (viewUiproperties == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(viewUiproperties);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 将表字段保存到view_uiproperties表中
     */
    /*@AutoLog(value = "查询出数据库表中的全部字段")
    @ApiOperation(value = "查询出数据库表中的全部字段", notes = "查询出数据库表中的全部字段")
    @GetMapping(value = "/saveColumn")
    public void saveColumn(@RequestParam(name = "tableName") String tableName) {

        List<DatabaseVO> columnNames = databaseUtil.getColumn(tableName);
        for (int i = 0; i < columnNames.size(); i++) {
            DatabaseVO databaseVO = columnNames.get(i);

            viewUipropertiesService.saveColumn(databaseVO,i);

            databaseVO = null;
        }
    }*/

    public  String replaceUpperCase(String str) {
        StringBuffer sb = new StringBuffer();
        sb.append(str);
        int count = sb.indexOf("_");
        while (count != 0) {
            int num = sb.indexOf("_", count);
            count = num + 1;
            if (num != -1) {
                char ss = sb.charAt(count);
                char ia = (char) (ss - 32);
                sb.replace(count, count + 1, ia + "");
            }
        }
        String result = sb.toString().replaceAll("_", "");
        return result;
    }

    public String replaceUnderLineAndUpperCase(String str) {
        StringBuffer sb = new StringBuffer();
        sb.append(str);
        int count = sb.indexOf("_");
        while (count != 0) {
            int num = sb.indexOf("_", count);
            count = num + 1;
            if (num != -1) {
                char ss = sb.charAt(count);
                char ia = (char) (ss - 32);
                sb.replace(count, count + 1, ia + "");
            }
        }
        String result = sb.toString().replaceAll("_", "");
        return StringUtils.capitalize(result);
    }

    /**
     * 查询出对应表数据库中的所有表字段
     */
    @AutoLog(value = "查询出数据库表中的全部字段")
    @ApiOperation(value = "查询出数据库表中的全部字段", notes = "查询出数据库表中的全部字段")
    @GetMapping(value = "/getColumnNames")
    public Result<?> ColumnNames(@RequestParam(name = "tableName") String tableName,
                                 @RequestParam(name = "parentId") String parentId) {
        Result result = new Result();
        QueryWrapper<ViewUiproperties> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> columnNames = viewUipropertiesService.list(queryWrapper);
        result.setResult(columnNames);
        return result;
    }


    /**
     * 刷新，查出对应表数据库中的所有表字段，对比，将新增加的表字段添加到字段配置表中
     */
    @AutoLog(value = "刷新表字段")
    @ApiOperation(value = "刷新表字段", notes = "刷新表字段")
    @GetMapping(value = "/refreshTableField")
    public Result<?> refreshTableField(@RequestParam(name = "tableName") String tableName,
                                       @RequestParam(name = "parentId") String parentId) {
        Result result = new Result();
        QueryWrapper<ViewUiproperties> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> list = viewUipropertiesService.list(queryWrapper);


        List<DatabaseVO> list2 = databaseUtil.getColumn(tableName);

        for(int i=0;i<list2.size();i++){
            boolean bf=true;
            for(int j=0;j<list.size();j++){
                if(list2.get(i).getColumnName().equals(list.get(j).getUiFieldname())){
                    bf=false;
                    break;
                }

            }
            if (bf) {
                viewUipropertiesService.saveColumn(list2.get(i),list.size());
                DatabaseVO databaseVO = list2.get(i);
                viewUipropertiesService.saveColumn(parentId,"0",databaseVO,i);
                databaseVO = null;
            }



        }

        result.setSuccess(true);
        return result;
    }



    /**
     * 拖拽排序
     *
     * @param viewUiproperties
     * @return
     */
    @AutoLog(value = "UI属性-拖拽排序")
    @ApiOperation(value = "UI属性-拖拽排序", notes = "UI属性-拖拽排序")
    @PutMapping(value = "/dragEdit")
    public Result<ViewUiproperties> dragEdit(@RequestBody List<ViewUiproperties> viewUiproperties) {
        Result<ViewUiproperties> result = new Result<ViewUiproperties>();
        List<ViewUiproperties> vup = new ArrayList<>();
        for (int i = 0; i < viewUiproperties.size(); i++) {
            ViewUiproperties viewUipropertie=new ViewUiproperties();
            viewUipropertie= viewUiproperties.get(i);
            //从数据库中查询数据
            QueryWrapper<ViewUiproperties> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", viewUipropertie.getId());
            ViewUiproperties one = viewUipropertiesService.getOne(queryWrapper);

            one.setUiOrder(i);
            vup.add(one);
            one=null;
            viewUipropertie=null;
        }

        boolean ok = viewUipropertiesService.saveOrUpdateBatch(vup);
        //TODO 返回false说明什么？
        if (ok) {
            result.success("修改成功!");
        }


        return result;
    }


    private Object apply(DatabaseVO y) {
        return viewUipropertiesService.saveColumn(y, 200);
    }
}
